package com.deyou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.deyou.Constants;
import com.deyou.R;
import com.deyou.adapter.FeedBackGVItemAdapter;
import com.deyou.base.BaseActivity;
import com.deyou.callback.ServerApi;
import com.deyou.model.SimpleResponse;
import com.deyou.util.AESUtil;
import com.deyou.util.Logger;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.yanzhenjie.album.Album;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static android.R.attr.navigationBarColor;
import static android.R.attr.statusBarColor;

public class FeedBackActivity extends BaseActivity implements GridView.OnItemClickListener {

    @BindView(R.id.iv_left_back)
    ImageView ivLeftBack;
    @BindView(R.id.tv_mid_title)
    TextView tvMidTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.et_feedback)
    EditText etFeedback;
    @BindView(R.id.gv_feedback_img)
    GridView gvFeedbackImg;
    @BindView(R.id.activity_feed_back)
    LinearLayout activityFeedBack;

    private FeedBackGVItemAdapter mAdapter;
    private ArrayList<String> mImageList = new ArrayList<>();
    private String feedbackImgUrls;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feed_back);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        tvMidTitle.setText("意见反馈");
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText("提交");
        tvRight.setTextColor(getResources().getColor(R.color.color_FF832D));
        mAdapter = new FeedBackGVItemAdapter(this);
        gvFeedbackImg.setAdapter(mAdapter);

        gvFeedbackImg.setOnItemClickListener(this);
    }

    @Override
    protected boolean translucentStatusBar() {
        return false;
    }

    @OnClick({R.id.iv_left_back, R.id.tv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_left_back:
                finish();
                break;
            case R.id.tv_right:
                if (TextUtils.isEmpty(etFeedback.getText().toString())){
                    showToast("请说点什么吧...");
                    return;
                }
                commitFeedBack();
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (mImageList.size() == 9) {
            Album.gallery(this)
                    .requestCode(999) // 请求码，返回时onActivityResult()的第一个参数。
                    .checkedList(mImageList) // 要预览的图片list。
                    .currentPosition(position) // 预览的时候要显示list中的图片的index。
                    .checkFunction(true) // 预览时是否有反选功能。
                    .start();
        } else if (mImageList.size() < 9 && mImageList.size() > 0) {
            if (position == mImageList.size()) {
                Album.album(this)
                        .requestCode(999) // 请求码，返回时onActivityResult()的第一个参数。
                        .title("图库") // 配置title。
                        .selectCount(9) // 最多选择几张图片。
                        .columnCount(3) // 相册展示列数，默认是2列。
                        .camera(true) // 是否有拍照功能。
                        .checkedList(mImageList) // 已经选择过得图片，相册会自动选中选过的图片，并计数。
                        .start();
            } else {
                Album.gallery(this)
                        .requestCode(999) // 请求码，返回时onActivityResult()的第一个参数。
                        .checkedList(mImageList) // 要预览的图片list。
                        .currentPosition(position) // 预览的时候要显示list中的图片的index。
                        .checkFunction(true) // 预览时是否有反选功能。
                        .start();
            }
        } else {
            Album.album(this)
                    .requestCode(999) // 请求码，返回时onActivityResult()的第一个参数。
                    .title("图库") // 配置title。
                    .selectCount(9) // 最多选择几张图片。
                    .columnCount(3) // 相册展示列数，默认是2列。
                    .camera(true) // 是否有拍照功能。
                    .checkedList(mImageList) // 已经选择过得图片，相册会自动选中选过的图片，并计数。
                    .start();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 999) {
            if (resultCode == RESULT_OK) { // Successfully.
                // 不要再次质疑你的眼睛，还是这么简单。
                mImageList = Album.parseResult(data);
                if (null == mImageList || mImageList.size() <= 0)
                    return;
                mAdapter.setImgs(mImageList);
                uploadFeedbBackImg();
            } else if (resultCode == RESULT_CANCELED) { // User canceled.
                // 用户取消了操作。
            }
        }
    }

    /**
     * 上传正面认证照片
     */
    private void uploadFeedbBackImg() {
        final ArrayList<File> files = new ArrayList<>();
        if (mImageList != null && mImageList.size() > 0) {
            for (int i = 0; i < mImageList.size(); i++) {
                files.add(new File(mImageList.get(i)));
            }
        }
        Observable.create(new ObservableOnSubscribe<Progress>() {
            @Override
            public void subscribe(@NonNull final ObservableEmitter<Progress> e) throws Exception {
                OkGo.<String>post(Urls.uploadImg)//
                        .tag(this)//
                        .addFileParams("file", files)//
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                e.onComplete();
                                SimpleResponse resp = new Gson().fromJson(response.body(), SimpleResponse.class);
                                if (resp.code == 1 && !TextUtils.isEmpty(resp.data))
                                    feedbackImgUrls = resp.data;
                                else
                                    feedbackImgUrls = "";
                            }

                            @Override
                            public void onError(Response<String> response) {
                                e.onError(response.getException());
                            }

                            @Override
                            public void uploadProgress(Progress progress) {
                                e.onNext(progress);
                            }
                        });
            }
        })//
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                       showLoading("图片上传中...");
                    }
                })//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Observer<Progress>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull Progress progress) {
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();
                        showToast("上传出错  \n" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                    }
                });
    }

    private void commitFeedBack(){
        JSONObject object = new JSONObject();
        try {
            object.put("feedbackContent", etFeedback.getText().toString());
            object.put("feedbackPic", feedbackImgUrls);
            object.put("userId", SPUtils.getStringByKey(FeedBackActivity.this, Constants.UserId));
            String paramJson = object.toString();

            ServerApi.getString(Urls.addFeedBack, "", AESUtil.encrypt(paramJson))//
                    .subscribeOn(Schedulers.io())//
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@io.reactivex.annotations.NonNull Disposable disposable) throws Exception {
                            showLoading("上传意见反馈中...");
                        }
                    })//
                    .observeOn(AndroidSchedulers.mainThread())  //
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(@io.reactivex.annotations.NonNull String s) {
                            SimpleResponse resp = new Gson().fromJson(s, SimpleResponse.class);
                            if (null != resp && resp.code == 1){
//                                finish();
                                showToast("感谢您的反馈...");
                            } else {
                                showToast(resp.msg);
                            }
                        }

                        @Override
                        public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                            e.printStackTrace();            //请求失败
                            showToast("意见反馈上传失败");
                            dismissLoading();
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
